package cn.wolfcode.rbac.web.intercptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.CurrentUtil;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * @version 1.0
 * @Author:Cao Zhijian
 * @DATE:2020/12/27 0027 22:20:59
 */
@Component
public class SecurityIntercptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.判断用户是否是超级管理员
        Employee employee = CurrentUtil.getCurrent();
        System.out.println(employee.toString());
        if(employee.getAdmin()){
            return true;
        }

        // 2.判断访问的资源是否有贴有注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if(methodAnnotation == null){
            return true;
        }

        // 3.如果方法上贴有注解并且该用户拥有该权限，则放行
        Set<String> expression = CurrentUtil.getExpression();
        if(expression.contains(methodAnnotation.value()[1])){
            return true;
        }

        // 如果没有这个权限则进行拦截,并跳转
        request.getRequestDispatcher("/views/common/nopermission.jsp").forward(request,response);
        return false;
    }
}
